<template>
  <div class="app">
    <div class="top">
      <el-button type="primary" @click="newGiftBag()">添加礼包方案</el-button>
    </div>

    <el-table v-loading="loading" :data="goodList">
      <el-table-column
        label="id"
        width="100"
        align="center"
        prop="productLevel"
      >
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column width="200" label="礼包名称" prop="name" />
      <el-table-column label="升级商品" align="center" prop="upgradeGood">
        <template slot-scope="{ row }">
          <el-table
            ref="upgradeGoodTable"
            :data="[row.upgradeGood]"
            tooltip-effect="light"
            style="width: 100%"
          >
            <el-table-column prop="goodId" label="商品id" align="center" />

            <el-table-column prop="goodName" label="商品名称">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.goodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.goodName }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="赠送商品" align="center" prop="oneGoods">
        <template slot-scope="{ row }">
          <el-table
            ref="oneGoodsTable"
            :data="row.oneGoods"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="oneGoodId" label="商品id" align="center" />

            <el-table-column prop="oneGoodName" label="商品名称">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.oneGoodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.oneGoodName }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="oneGoodNumber"
              label="商品数量"
              align="center"
            />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        label="升级等级"
        width="150"
        align="center"
        prop="productLevel"
      >
        <template slot-scope="{ row }">
          <el-tag size="mini" v-if="row.productLevel != 0">{{
            forrmatterEnmu(DictData.memberPurchase, row.productLevel)
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <div>
            <el-tooltip content="编辑" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="editGiftBag(scope.$index, scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deleteGiftBag(scope.$index)"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑升级礼包弹窗 -->
    <el-dialog
      :visible.sync="editOpen"
      width="1000px"
      @close="handleDialogClose()"
    >
      <!-- 标题 -->
      <template #title>
        <div style="text-align: center; font-size: 18px; font-weight: bold">
          {{ title }}
        </div>
      </template>

      <template>
        <div class="gift-package-input">
          <span class="label">礼包名称</span>
          <el-input
            clearable
            v-model="formData.name"
            placeholder="请输入礼包名称"
          ></el-input>
        </div>
      </template>

      <template>
        <div class="gift-package-input">
          <span class="label">升级商品</span>
          <el-button type="primary" @click="selectGoods()">选择商品</el-button>
        </div>
        <div class="heigt">
          <div class="gift-package-text" style="border: none">
            <span>必须且只能选择一个商品</span>
          </div>
          <el-table :data="formData.upgradeGood ? [formData.upgradeGood] : []">
            <!-- 全选框列 -->
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>

            <el-table-column
              prop="goodId"
              label="商品id"
              width="80"
              align="center"
            />

            <el-table-column prop="goodName" label="商品名称" width="200">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.goodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.goodName }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  plain
                  @click="editDelect(scope.$index, scope.row, true)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <template>
        <div class="gift-package-input">
          <span class="label">升级等级</span>
          <el-select
            v-model="formData.productLevel"
            placeholder="请选择升级等级"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
      </template>

      <template>
        <div class="gift-package-input">
          <span class="label">赠送商品</span>
          <el-button type="primary" @click="presentGoods()">选择商品</el-button>
        </div>

        <div class="heigt">
          <div class="gift-package-text" style="border: none">
            <span>最多可添加20个商品</span>
          </div>

          <el-table :data="formData.oneGoods">
            <!-- 全选框列 -->
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>

            <el-table-column
              prop="oneGoodId"
              label="商品id"
              width="80"
              align="center"
            />

            <el-table-column prop="oneGoodName" label="商品名称" width="200">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.oneGoodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.oneGoodName || row.goodName }}</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="赠送数量" width="250" align="center">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.oneGoodNumber"
                  :min="0"
                  @change="handleQuantityChange(scope.$index, scope.row)"
                  label="数量"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="danger"
                  plain
                  @click="editDelect(scope.$index, scope.row, false)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <!-- <template>
        <div class="gift-package-input">
          <span class="label">是否启用</span>
          <el-switch
            v-model="formData.status"
            active-color="#13ce66"
            inactive-color="#999"
          >
          </el-switch>
        </div>
      </template> -->

      <template>
        <div class="bottom">
          <el-button @click="editOpen = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
      </template>

      <!-- 选择商品 -->
      <el-dialog
        title="商品选择"
        :visible.sync="detailOpen"
        width="800px"
        append-to-body
      >
        <!-- 搜索 -->
        <!-- <template v-if="showSearch">
          <div style="margin-bottom: 15px">
            <el-input
              placeholder="根据商品名称和商品ID搜索"
              v-model="queryParams.query"
              class="input-with-select"
              @keyup.enter.native="handleQueryDetail()"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleQueryDetail()"
              ></el-button>
            </el-input>
          </div>
        </template> -->

        <template v-if="!showSearch">
          <div class="gift-package-container">
            <div class="gift-package-text">
              <span>下列商品为云库存商品</span>
            </div>
          </div>
        </template>

        <!-- 表单 -->
        <template v-if="showSearch">
          <el-table
            ref="goodsTable"
            :data="goodsDetailList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <!-- 全选框列 -->
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column
              prop="goodId"
              label="ID"
              width="80"
              align="center"
            />

            <el-table-column prop="goodName" label="名称">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.goodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.goodName }}</div>
                </div>
              </template>
            </el-table-column>

            <template v-if="showSearch">
              <el-table-column
                prop="retailPrice"
                label="成本价"
                align="center"
              />

              <el-table-column
                prop="goodInventory"
                label="库存"
                align="center"
              />

              <el-table-column label="商品来源" align="center"
                ><span>本商城商品</span>
              </el-table-column>
            </template>
          </el-table>
        </template>
        <template v-else>
          <el-table
            ref="goodsTable"
            :data="goodsDetailList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <!-- 全选框列 -->
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column
              prop="goodId"
              label="ID"
              width="80"
              align="center"
            />

            <el-table-column prop="goodName" label="名称">
              <template slot-scope="{ row }">
                <div style="display: flex; align-items: center">
                  <div>
                    <image-preview
                      :src="row.goodImg"
                      height="50"
                      width="50"
                    ></image-preview>
                  </div>
                  <div>{{ row.goodName }}</div>
                </div>
              </template>
            </el-table-column>

            <template v-if="showSearch">
              <el-table-column
                prop="retailPrice"
                label="成本价"
                align="center"
              />

              <el-table-column
                prop="goodInventory"
                label="库存"
                align="center"
              />

              <el-table-column label="商品来源" align="center"
                ><span>本商城商品</span>
              </el-table-column>
            </template>
          </el-table>
        </template>
        <div class="show_center">
          <el-button type="primary" @click="menuAdd()">{{
            showSearch ? "选择" : "确认"
          }}</el-button>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="commoditytTtal"
          >
            <!--  @current-change="getList" -->
            >
          </el-pagination>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectGiftBag,
  selectGiftBagCommodity,
  editPutGiftBagCommodity,
  editPostGiftBagCommodity,
  delectGiftBagCommodity,
} from "@/api/inventory/giftBag";
import { forrmatterEnmu } from "@/utils/index";
export default {
  name: "Good",
  dicts: ["member_agency_level"],
  data() {
    return {
      //修改前数据id
      id: -1,
      //记录新增修改
      boolRecord: false,
      // 遮罩层
      loading: true,
      //页面数据
      goodList: [],
      //商品数据
      goodsDetailList: [],
      // 是否显示弹出层
      editOpen: false,
      detailOpen: false,
      // 弹出层标题
      title: "",
      // 礼包总条数
      total: 0,
      // 商品总条数
      commoditytTtal: 0,
      //下拉菜单
      selectedValue: null, // 绑定选中的值
      options: [
        { value: 3, label: "共享店主" },
        { value: 4, label: "联创" },
        { value: 5, label: "区域运营中心" },
        { value: 6, label: "总裁" },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // query: null,
        // level: null,
      },
      // 区分商品和赠品
      showSearch: true,
      // 用于存储选中的行数据（商品）
      selectedRows: [],
      // 标志位，防止重复调用
      isHandlingSelectionChange: false,
      //编辑
      // editGiftBagList: [],
      //单个页面数据临时转存
      formData: {
        status: 1,
        name: "",
        //商品升级
        upgradeGood: null,
        //商品赠送
        oneGoods: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    forrmatterEnmu,
    /** 查询 */
    getList() {
      this.loading = true;
      selectGiftBag(this.queryParams).then((response) => {
        this.goodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    newGiftBag() {
      this.title = `添加升级礼包`;
      this.editOpen = true;
      //添加状态
      this.boolRecord = true;
      this.formData = {
        status: 1,
        name: "",
        upgradeGood: null,
        oneGoods: [],
      };
    },
    open(str) {
      this.$message({
        message: str,
        type: "warning",
      });
    },
    verify() {
      let name = this.formData.name;
      if (!name || name.trim() === "") {
        return { valid: false, message: "礼包名称不能为空" };
      }
      // 校验是否至少选中了一件商品
      if (!this.formData.upgradeGood) {
        return { valid: false, message: "至少需要选中一件升级商品" };
      }
      if (!this.formData.oneGoods || this.formData.oneGoods.length == 0) {
        return { valid: false, message: "至少需要选中一件赠送商品" };
      }

      return { valid: true, message: "校验通过" };
    },
    //保存
    onSubmit() {
      //校验
      const verMessage = this.verify();
      if (!verMessage.valid) {
        this.open(verMessage.message);
        return;
      }
      let boolen = false;
      let submitGiftBag = [];
      if (this.id != -1) {
        this.formData.upgradeGood.id = this.id;
      }
      this.formData.oneGoods.forEach((good) => {
        if (!good.oneGoodNumber > 0) {
          this.open("赠送商品数量不能为 0");
          boolen = true;
          return;
        }
        let newGiftBag = Object.assign(
          {},
          { name: this.formData.name },
          this.formData.upgradeGood,
          good
        );
        submitGiftBag.push(newGiftBag);
      });
      if (boolen) {
        return;
      }

      if (this.boolRecord) {
        editPostGiftBagCommodity(submitGiftBag).then((response) => {
          this.getList();
        });
      } else {
        editPutGiftBagCommodity(submitGiftBag).then((response) => {
          this.getList();
        });
      }

      this.editOpen = false;
    },
    //升级商品
    selectGoods() {
      this.detailOpen = true;
      this.showSearch = true;
      this.handleQueryDetail();
    },
    //赠送商品
    presentGoods() {
      this.goodsDetailList = [];
      this.detailOpen = true;
      this.showSearch = false;
      let present = {
        classOneId: 2,
        queryParams: this.queryParams,
      };
      selectGiftBagCommodity(present).then((response) => {
        this.commoditytTtal = response.total;
        this.goodsDetailList = response.rows;
        this.$refs.goodsTable.clearSelection();
      });
    },
    //查询操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 监听表格的选中变化
    handleSelectionChange(select, row) {
      if (this.showSearch) {
        if (this.isHandlingSelectionChange) {
          this.$refs.goodsTable.clearSelection();
          this.isHandlingSelectionChange = false;
          return;
        }
        this.isHandlingSelectionChange = true;
        let selectData = null;
        if (select.length > 1) {
          this.$refs.goodsTable.clearSelection();
          selectData = select.pop();
          this.$refs.goodsTable.toggleRowSelection(selectData, true);
        } else {
          selectData = select[0];
          this.$refs.goodsTable.toggleRowSelection(selectData, true);
        }
        this.selectedRows = [selectData];
        this.isHandlingSelectionChange = false;
      } else {
        this.selectedRows = select; // 更新选中的行数据
      }
    },
    //选择商品
    menuAdd() {
      if (this.showSearch) {
        const upgradClass = this.selectedRows[0];
        this.formData.upgradeGood = {
          goodImg: upgradClass.goodImg,
          goodId: upgradClass.goodId,
          goodName: upgradClass.goodName,
        };
        this.formData.productLevel = upgradClass.productLevel;
      } else {
        let rowsList = [];
        this.selectedRows.forEach((row) => {
          const rowClass = {
            oneGoodImg: row.goodImg,
            oneGoodId: row.goodId,
            oneGoodName: row.goodName,
            oneGoodNumber: 0,
            createTime: row.createTime,
          };
          rowsList.push(rowClass);
        });
        this.formData.oneGoods = this.formData.oneGoods.concat(rowsList);
      }

      this.selectedRows = [];
      this.detailOpen = false;
    },
    editDelect(index, row, bool) {
      if (bool) {
        this.formData.upgradeGood = null;
      } else {
        this.formData.oneGoods.splice(index, 1);
      }
    },

    //编辑
    editGiftBag(index, row) {
      this.title = `编辑升级礼包`;
      //编辑状态
      this.boolRecord = false;
      this.editOpen = true;
      this.formData = JSON.parse(JSON.stringify(row));
      this.id = row.upgradeGood.goodId;
    },
    handleDialogClose() {
      this.formData = {
        status: 1,
        name: "",
        upgradeGood: null,
        oneGoods: [],
      };
    },
    deleteGiftBag(index) {
      const removedGoods = this.goodList.splice(index, 1);
      delectGiftBagCommodity(removedGoods[0].upgradeGood.goodId).then(
        (response) => {
          this.getList();
        }
      );
    },
    handleQuantityChange(index, row) {},
    //升级商品查询
    handleQueryDetail() {
      // this.selectedRows = [];

      this.goodsDetailList = [];
      this.queryParams.flag = 1;
      selectGiftBagCommodity(this.queryParams).then((response) => {
        this.commoditytTtal = response.total;
        this.goodsDetailList = response.rows;
        delete this.queryParams.fal;
        this.$refs.goodsTable.clearSelection();
      });
    },
  },
};
</script>
<style lang="less" scoped>
.app {
  font-size: 18rpx;
  color: #1a1a1a;
  margin: 20px;
  .top {
    margin-bottom: 25px;
  }
  .gift-package-input {
    display: flex;
    align-items: center;
    margin-bottom: 15px; /* 可根据需要调整间距 */
    .label {
      margin-right: 8px; /* 标签和输入框之间的间距 */
      font-size: 14px;
      width: 70px;
      color: #333; /* 可根据需要调整字体颜色 */
    }
  }
  .bottom {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;
  }
}
.heigt {
  margin-left: 150px;
  margin-bottom: 50px;
}
.gift-package-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
.gift-package-text {
  border: 1px solid #f87e7e; /* 未来可能添加的边框 */
  font-size: 13px; /* 仅与文本相关的样式 */
  color: #f40606;
  padding: 5px;
}
.show_center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
.pagination-container {
  text-align: right; /* 设置右对齐 */
  margin-top: 20px; /* 可选：增加一些上边距 */
}
</style>
